package com.example.springboot.web;

import com.example.springboot.bean.Menu;
import com.example.springboot.bean.Result;
import com.example.springboot.biz.BizException;
import com.example.springboot.biz.MenuBiz;
import com.example.springboot.mapper.MenuMapper;
import com.example.springboot.util.Utils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

// 网站后台管理控制器  对应  IndexAction
@Controller
public class BackAction {

    @Resource
    private MenuMapper mm;

    @Resource
    private MenuBiz mb;

    @RequestMapping("back")
    public String back(Model model){
        model.addAttribute("menus", mm.selectRootMenu());
        return "back";
    }

    @RequestMapping("delMenu")
    @ResponseBody
    public Result delMenu(int id){
        try {
            mb.removeById(id);
            return new Result(1, "菜单删除成功!", null);
        } catch (BizException e) {
            return new Result(0, e.getMessage(), null);
        }
    }

    @RequestMapping("modMenu")
    @ResponseBody
    public Result modMenu(@Valid Menu menu, Errors errors){
        try {
            mb.modify(menu, errors);
            return new Result(1, "菜单修改成功!", null);
        } catch (BizException e) {
            List<ObjectError> es = (List<ObjectError>)e.getData();
            String msg = Utils.getErrors(es,"name");
            return new Result(0, msg, null);
        }
    }

}
